import express from 'express';
import {client, billTypeCounts} from './scheme.js';

const financialRoute = express.Router();

financialRoute.post('/getMonthReport', async (req, res) => {
  const {param: {user: {email}, filter}} = req.body;
  const {time} = filter;
  const userProfile = await client.user.findFirstOrThrow({
    where: {email: email},
    include: {account: true}
  });
  const startDate = new Date(time);
  const endTimestamp = (new Date(time)).setMonth(startDate.getMonth() + 1);
  const userAccountsWithBills = await client.account.findMany({
    where: {ownerID: userProfile.userID},
    select: {
      accountID: true,
      accountName: true,
      bill: {
        where: {
          AND: [
            {time: {gte: startDate}},
            {time: {lt: new Date(endTimestamp)}}
          ]
        }
      }
    }
  });
  const resultDataArray = Array<{
    total: number, percentage: number, billType: number
  }>(billTypeCounts);
  for( let i = 0; i < billTypeCounts; i++ ) {
    resultDataArray[i] = {total: 0, percentage: 0, billType: i};
  }
  for( let i = 0; i < userAccountsWithBills.length; i++ ) {
    for( let j = 0; j < userAccountsWithBills[i].bill.length; j++) {
      const cursor = userAccountsWithBills[i].bill[j];
      if(cursor.billType === 0) {
        continue;
      }
      resultDataArray[cursor.billType].total += cursor.cost.toNumber();
    }
  }
  let totalCost = 0;
  resultDataArray.map((elem) => {totalCost += elem.total;});
  for( let i = 0; i < billTypeCounts; i++ ) {
    resultDataArray[i].percentage += resultDataArray[i].total / totalCost;
  }
  try {
    return res.json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 200},
      result: {
        description: '查询完成',
        filter: {...filter},
        summary: resultDataArray.filter(
          (elem) => elem.percentage === 0 ? false : true
        ).map((elem) => {
          return {
            type: elem.billType,
            sum: elem.total,
            percentage: elem.percentage
          };
        })
      }
    });
  } catch(e) {
    console.log(e);
    return res.json({
      timestamp: new Date().getTime(),
      api: {version: 'v1.0', status: 403},
      result: {
        description: '未找到目标额度'
      }
    });
  }
});

export default financialRoute;